android - 如何使用LiveData和RxJava处理错误?
android - How to handle error by using LiveData and RxJava?
我是新手android architecture components,在题中卡了好几天
我使用LiveDataReactiveStreams来转换Livedata和Flowable,除了处理RxJava的onError外,它们都很好用。
livedata = LiveDataReactiveStreams.fromPublisher(
// bookRepository.getAll() return a Flowable
bookRepository.getAll().map {
val allBookNames = mutableListOf<String>()
it.forEach {
allBookNames.add(it.name)
}
return@map allBookNames.toList()
}
)
我看到了 如何使用 LiveData 处理错误状态?
并发现我可以
包装我的数据以处理我的错误
或者像@Nikola Despotoski说的那样使用MediatorLiveData,但是还有一个问题是Flowable onComplete() is never called.
是否有更好的方法来解决这个问题或关于我忽略的这两个解决方案的任何细节?
LiveDataReactiveStreams.fromPublisher(
Observable.just(1,2)
.map { LiveDataResult(it, null) }
.onErrorReturn {
it.printStackTrace()
LiveDataResult(null, it)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable(BackpressureStrategy.MISSING)
class LiveDataResult<T>(val data: T?, val error: Throwable?)
然后在UI中你可以处理结果或错误
我是新手android architecture components,在题中卡了好几天
我使用LiveDataReactiveStreams来转换Livedata和Flowable,除了处理RxJava的onError外,它们都很好用。
livedata = LiveDataReactiveStreams.fromPublisher(
// bookRepository.getAll() return a Flowable
bookRepository.getAll().map {
val allBookNames = mutableListOf<String>()
it.forEach {
allBookNames.add(it.name)
}
return@map allBookNames.toList()
}
)
我看到了 如何使用 LiveData 处理错误状态? 并发现我可以
包装我的数据以处理我的错误
或者像@Nikola Despotoski说的那样使用MediatorLiveData,但是还有一个问题是Flowable onComplete() is never called.
是否有更好的方法来解决这个问题或关于我忽略的这两个解决方案的任何细节?
LiveDataReactiveStreams.fromPublisher(
Observable.just(1,2)
.map { LiveDataResult(it, null) }
.onErrorReturn {
it.printStackTrace()
LiveDataResult(null, it)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable(BackpressureStrategy.MISSING)
class LiveDataResult<T>(val data: T?, val error: Throwable?)
然后在UI中你可以处理结果或错误